package com.exp04;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

@WebServlet(name = "ShowSessionInfo",value="/session")
public class ShowSessionInfo extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html,charset=utf-8");
        HttpSession session = request.getSession(true);
        String header = null;
        String info = "Information about your session";
        Integer accessCount = (Integer) session.getAttribute("accessCount");
        if (accessCount == null){
            accessCount =1;
            header = "Welcome, enter this page first time!";
        }else {
            header = "Welcome Back!";
            accessCount = accessCount+1;
        }
        session.setAttribute("accessCount",accessCount);
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<body style=\"text-align :center;font-family:'FiraCode Nerd Font',serif\" >");
        out.println("<h2>"+header + "</h2>" +"<h3>" +info+"</h3>");
        out.println("<table border='1' style=\"text-align:center;margin:0px auto\">");
        out.println("<tr bgcolor=\"ffad0\"><td><b>Info Type</b><td><b>Value</b>\n");
        out.println("<tr><td>ID:<td>"+session.getId()+"\n");
        out.println("<tr><td>Create Time:<td>");
        out.println(""+new Date(session.getCreationTime())+"\n");
        out.println("<tr><td>Time of last access:<td>");
        out.println(""+new Date(session.getLastAccessedTime())+"\n");
        out.println("<tr><td>Access number:<td>"+accessCount+"\n");
        out.println("</table>");
        out.println("</body>");
        out.println("</html>");
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
